package com.anlu.concurrent.ch1;

/**
 * 演示使用本地变量
 */
public class UseThreadLocal {

    //可以理解为 一个map，类型 Map<Thread,Integer>
    static ThreadLocal<Integer> threadLaocl = new ThreadLocal<Integer>(){
        @Override
        protected Integer initialValue() {
            return 1;
        }
    };

    public void startThreadArray(){
        Thread[] runs =new Thread[3];
        for (int i = 0; i < runs.length; i++) {
            runs[i]=new Thread(new TestThread(i));
        }
        for(int i=0;i<runs.length;i++){
            runs[i].start();
        }
    }

public static class TestThread  implements Runnable{
    int id;

    public TestThread(int id) {
        this.id = id;
    }

    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName()+":start:id="+this.id+";threadLaocl.get()="+threadLaocl.get());
        Integer s =threadLaocl.get();
        s=s+id;
        System.out.println("当前的s="+s);
        threadLaocl.set(s);
        System.out.println(Thread.currentThread().getName()+":"
                +threadLaocl.get());


    }

    public static void main(String[] args){
        UseThreadLocal test = new UseThreadLocal();
        test.startThreadArray();
    }
}





}
